import { ChatOllama } from '@langchain/ollama';
import { PromptTemplate } from "@langchain/core/prompts";
import { ToolManager } from "../ch08/tool-manager";

// query（查询）
// complaint（投诉）
// suggestion（建议）
// escalation（升级）
export interface CustomerIntent {
  type: "query" | "complaint" | "suggestion" | "escalation";
  confidence: number;
  entities: Record<string, any>;
}

export class CustomerServiceAgent {
  private llm: ChatOllama;
  private tools: ToolManager;
  private memory: any[] = [];

  constructor() {
    this.llm = new ChatOllama({
      baseUrl: 'http://192.168.31.159:11434',
      model: 'llama3.1:latest', // 使用您想要的模型
    });
    this.tools = new ToolManager();
  }

  private async analyzeIntent(message: string): Promise<CustomerIntent> {
    const prompt = PromptTemplate.fromTemplate(`
分析用户意图，只输出一个严格的 JSON 对象，不要有任何其他文字：

{{
  "type": "query|complaint|suggestion|escalation",
  "confidence": 0.0-1.0,
  "entities": {{
    "product": "产品名称",
    "issue": "问题描述",
    "urgency": "紧急程度"
  }}
}}

用户消息：{message}
历史对话：{history}
`);

    const response = await prompt.pipe(this.llm).invoke({
      message,
      history: this.memory.slice(-3).map(m => `${m.role}: ${m.content}`).join("\n")
    });

    // 提取 JSON（处理 LLM 可能返回的额外文字）
    const content = response.content as string;
    const jsonMatch = content.match(/\{[\s\S]*\}/);
    
    if (!jsonMatch) {
      // 如果无法解析，返回默认意图
      return {
        type: "query",
        confidence: 0.5,
        entities: {}
      };
    }

    try {
      return JSON.parse(jsonMatch[0]);
    } catch (e) {
      console.warn("意图解析失败，使用默认值:", e);
      return {
        type: "query",
        confidence: 0.5,
        entities: {}
      };
    }
  }

  private async generateResponse(
    message: string,
    intent: CustomerIntent,
    context: any
  ): Promise<string> {
    const prompt = PromptTemplate.fromTemplate(`
你是专业的客服代表，基于用户意图和上下文生成回复。

用户意图：{intent}
上下文信息：{context}
历史对话：{history}

要求：
1. 语气友好专业
2. 针对意图类型调整回复策略
3. 提供具体解决方案
4. 必要时引导用户提供更多信息

用户消息：{message}
回复：`);

    const response = await prompt.pipe(this.llm).invoke({
      message,
      intent: JSON.stringify(intent),
      context: JSON.stringify(context),
      history: this.memory.slice(-3).map(m => `${m.role}: ${m.content}`).join("\n")
    });

    return response.content as string;
  }

  async processMessage(message: string): Promise<{
    response: string;
    intent: CustomerIntent;
    actions: string[];
    shouldEscalate: boolean;
  }> {
    // 1. 意图分析
    const intent = await this.analyzeIntent(message);

    // 2. 根据意图执行相应工具
    const actions: string[] = [];
    const context: any = {};

    if (intent.type === "query") {
      // 知识检索
      const searchResult = await this.tools.execute("search", {
        query: message
      });
      context.searchResult = searchResult;
      actions.push("知识检索");
    }

    if (intent.confidence < 0.7) {
      // 低置信度，需要澄清
      context.needsClarification = true;
      actions.push("请求澄清");
    }

    // 3. 生成回复
    const response = await this.generateResponse(message, intent, context);

    // 4. 更新记忆
    this.memory.push({ role: "user", content: message });
    this.memory.push({ role: "assistant", content: response });

    // 5. 判断是否需要升级
    const shouldEscalate = intent.type === "escalation" ||
      (intent.type === "complaint" && intent.confidence > 0.8);

    return {
      response,
      intent,
      actions,
      shouldEscalate
    };
  }

  async createTicket(userInfo: any, issue: string): Promise<string> {
    // 模拟工单创建
    const ticketId = `TKT-${Date.now()}`;
    console.log(`创建工单 ${ticketId}:`, { userInfo, issue });
    return ticketId;
  }
}
